<?php
namespace App\Bots;
use QL\QueryList;
use App\Models\Movie;
use GuzzleHttp\Exception\RequestException;
// 自动添加短评
class CommentBots
{
    protected $movie;
    protected $ql;
    public function __construct(Movie $movie)
    {
        $this->movie = $movie;
        $url = config('services.oss.douban.url') . '/' . $movie->douban_id;
        $ql = QueryList::getInstance();
        //QueryList::get($url);
        $ql->bind('myGet',function ($url,$args = null,$otherArgs = []){
            try{
                $this->get($url,$args,$otherArgs);
            }catch(RequestException $e){
                $this->setHtml('');
            }
            return $this;
        });
        $this->ql = $ql->myGet($url);
    }

    public function run()
    {
        return $this->getComments();
    }

    protected function getComments()
    {
        $rules = [
            'author' => ['.comment-info>a', 'text'],
            // 采集内容
            'content' => ['.comment>p>span.short', 'html'],
            'content2' => ['.comment>p>span.hide-item.full', 'html'],
            'created_at' => ['.comment-info>span.comment-time', 'title'],
        ];
        return $this->ql->range('#hot-comments > .comment-item')
                        ->rules($rules)
                        ->query()
                        ->getData(function($item) {
                            if (!empty($item['content2'])) {
                                $item['content'] = $item['content2'];
                            }
                            unset($item['content2']);
                            return $item;
                        })
                        ->all();
    }
}
